'use strict';

// 光标管理
export const cursor = {
    // 获取当前光标位置
    get(element) {
        var CaretPos = 0;
        // IE Support
        if (document.selection) {
            element.focus();
            var Sel = document.selection.createRange();
            Sel.moveStart('character', -element.value.length);
            CaretPos = Sel.text.length;
        }
        // Firefox support
        else if (element.selectionStart || element.selectionStart == '0') {
            CaretPos = element.selectionStart;
        }
        return (CaretPos);
    },
    // 设置当前管标的位置
    set(element, pos) {
        if (element.setSelectionRange) {
            element.focus();
            element.setSelectionRange(pos, pos);
        } else if (element.createTextRange) {
            var range = element.createTextRange();
            range.collapse(true);
            range.moveEnd('character', pos);
            range.moveStart('character', pos);
            range.select();
        }
    },
    // 在光标处插入内容
    val: function (element, value) {
        if (document.selection) {
            element.focus();
            sel = document.selection.createRange();
            sel.text = value;
            sel.select();
        } else if (element.selectionStart || element.selectionStart == '0') {
            var startPos = element.selectionStart;
            var endPos = element.selectionEnd;
            var restoreTop = element.scrollTop;
            element.value = element.value.substring(0, startPos) + value + element.value.substring(endPos, element.value.length);
            if (restoreTop > 0) {
                element.scrollTop = restoreTop;
            }
            element.focus();
            element.selectionStart = startPos + value.length;
            element.selectionEnd = startPos + value.length;
        } else {
            element.value += value;
            element.focus();
        }
    }
}
